document.addEventListener('DOMContentLoaded', async function () {
    // 检查登录状态
    try {
        const loginResponse = await fetch('/api/v1/users/isLogin');
        const loginData = await loginResponse.json();

        if (!loginData.data.login) {
            // 未登录，跳转到登录页面
            window.location.href = '/login.html';
            return;
        }
    } catch (error) {
        console.error('检查登录状态失败:', error);
        window.location.href = '/login.html';
        return;
    }


    // ======== 发送邮件功能 ========
    document.getElementById('sendEmailBtn').addEventListener('click', async function () {
        try {
            // 1. 发送权限检查请求
            const response = await fetch('/api/v1/userTemplates/check-export-permission', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({}) // 根据接口要求传递必要参数
            });

            // 2. 检查HTTP状态码
            if (!response.ok) {
                throw new Error(`权限检查失败 (HTTP ${response.status})`);
            }

            // 3. 解析JSON数据
            const data = await response.json();

            // 4. 根据业务逻辑判断权限
            if (data.code === 200 && data.data?.isExport) {
                document.getElementById('send-modal').style.display = 'block';
            } else {
                showToast(data.message || '🚫 无发送权限');
            }
        } catch (error) {
            console.error('权限检查异常:', error);
            showToast('❌ 权限验证失败: ' + error.message);
        }
    });

    // ================== 修正后的文件上传逻辑 ==================
    // 限定作用域到发送弹窗内部
    const sendModal = document.getElementById('send-modal');
    const fileInput = sendModal.querySelector('#attachment');
    const fileInfo = sendModal.querySelector('.file-info');
    const uploadContainer = sendModal.querySelector('.file-upload');

    // 显示选中文件信息（增强多文件显示）
    fileInput.addEventListener('change', function () {
        const files = Array.from(this.files);
        const fileList = files.map((file, index) =>
            `${index + 1}. ${file.name} (${(file.size / 1024 / 1024).toFixed(2)}MB)`
        ).join('\n');

        fileInfo.textContent = files.length > 0
            ? `已选择 ${files.length} 个文件：\n${fileList}`
            : '未选择任何文件';
    });

    // 优化拖拽处理（兼容所有浏览器）
    uploadContainer.addEventListener('drop', function (e) {
        e.preventDefault();
        this.classList.remove('dragover');

        // 创建新的文件列表
        const dataTransfer = new DataTransfer();

        // 逐个添加文件（解决部分浏览器限制）
        Array.from(e.dataTransfer.files).forEach(file => {
            if (file.size > 10 * 1024 * 1024) {
                showToast(`文件 ${file.name} 超过10MB限制`);
                return;
            }
            dataTransfer.items.add(file);
        });

        // 更新文件输入（兼容旧浏览器写法）
        fileInput.files = dataTransfer.files;

        // 创建完整的事件对象（必须包含bubbles属性）
        const changeEvent = new Event('change', {
            bubbles: true,
            cancelable: true
        });
        fileInput.dispatchEvent(changeEvent);
    });

    // 增加手动选择的二次确认
    uploadContainer.querySelector('.custom-file-input').addEventListener('click', function () {
        // 清空旧选择避免覆盖
        fileInput.value = '';
    });


    const canvas = document.getElementById('canvas-content');
    const componentItems = document.querySelectorAll('.component-item');
    const importBtn = document.getElementById('importBtn');
    const exportBtn = document.getElementById('exportBtn');
    const previewBtn = document.getElementById('previewBtn');
    let selectedElement = null;

    // 组件模板
    const componentTemplates = {
        // 布局组件
        section: {
            type: 'section',
            html: `<div class="element-content">
                <section style="padding: 20px; border: 1px dashed #eee; min-height: 100px;">
                    <div style="text-align: center; color: #999;">区域布局</div>
                </section>
            </div>`,
            properties: ['布局']
        },
        columns: {
            type: 'columns',
            html: `<div class="element-content">
                <div style="display: flex; gap: 20px; min-height: 100px;">
                    <div style="flex: 1; padding: 20px; border: 1px dashed #eee;">
                        <div style="text-align: center; color: #999;">列 1</div>
                    </div>
                    <div style="flex: 1; padding: 20px; border: 1px dashed #eee;">
                        <div style="text-align: center; color: #999;">列 2</div>
                    </div>
                </div>
            </div>`,
            properties: ['布局']
        },

        // 基础组件
        heading: {
            type: 'heading',
            html: `<div class="element-content">
                <h2 contenteditable="true" style="margin: 10px 0;">标题文本</h2>
            </div>`,
            properties: ['文字']
        },
        text: {
            type: 'text',
            html: `<div class="element-content">
                <p contenteditable="true" style="margin: 10px 0;">编辑文本内容</p>
            </div>`,
            properties: ['文字']
        },
        divider: {
            type: 'divider',
            html: `<div class="element-content">
                <hr style="border: none; border-top: 1px dashed #ddd; margin: 20px 0;">
            </div>`,
            properties: ['分割线']
        },
        list: {
            type: 'list',
            html: `<div class="element-content">
                <ul contenteditable="true" style="margin: 10px 0; padding-left: 20px;">
                    <li>列表项 1</li>
                    <li>列表项 2</li>
                    <li>列表项 3</li>
                </ul>
            </div>`,
            properties: ['文字']
        },

        // 媒体组件
        image: {
            type: 'image',
            html: `<div class="element-content" style="text-align: center;">
                <div class="image-wrapper" style="position: relative; 
                       display: inline-block; 
                       overflow: hidden;
                       cursor: pointer;
                       min-width: 200px;
                       min-height: 150px;">
                    <input type="file" accept="image/*" style="display: none;">
                    <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect width='100' height='100' fill='%23f0f0f0'/%3E%3C/svg%3E" 
                         style="width: 100%;
                                height: 100%;
                                object-fit: cover;
                                display: block;">
                    <div class="upload-text" style="position: absolute; 
                          top: 50%; 
                          left: 50%; 
                          transform: translate(-50%, -50%); 
                          color: #999;
                          pointer-events: none;">点击上传图片</div>
                </div>
            </div>`,
            properties: ['图片']
        },
        video: {
            type: 'video',
            html: `<div class="element-content" style="text-align: center;">
                <div class="video-wrapper" style="position: relative; max-width: 600px; margin: 0 auto;">
                    <div class="video-placeholder" style="aspect-ratio: 16/9; background: #f5f5f5; display: flex; align-items: center; justify-content: center; cursor: pointer;">
                        <div style="color: #999;">点击设置视频链接</div>
                    </div>
                </div>
            </div>`,
            properties: ['视频']
        },
        icon: {
            type: 'icon',
            html: `<div class="element-content" style="text-align: center;">
                <div class="icon-selector" style="padding: 10px;">
                    <select style="padding: 5px;">
                        <option value="star">★ 星形</option>
                        <option value="heart">♥ 心形</option>
                        <option value="arrow">→ 箭头</option>
                    </select>
                    <span class="icon-display" style="font-size: 24px; margin-left: 10px;">★</span>
                </div>
            </div>`,
            properties: ['图标']
        },

        // 交互组件
        button: {
            type: 'button',
            html: `<div class="element-content" style="text-align: {{text-align}};">
                <button class="custom-button" style="padding: 8px 16px; background: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer;">
                    <span contenteditable="true">按钮文本</span>
                </button>
            </div>`,
            properties: ['按钮']
        },
        link: {
            type: 'link',
            html: `<div class="element-content" style="text-align: {{text-align}};">
                <a href="#" contenteditable="true" style="color: #1890ff; text-decoration: none;">链接文本</a>
            </div>`,
            properties: ['链接']
        },
        card: {
            type: 'card',
            html: `<div class="element-content">
                <div class="card" style="border: 1px solid #eee; border-radius: 4px; padding: 20px; background: white;">
                    <h3 contenteditable="true" style="margin-bottom: 10px;">卡片标题</h3>
                    <p contenteditable="true" style="color: #666;">卡片内容</p>
                </div>
            </div>`,
            properties: ['卡片']
        }
    };

    // 为不同类型的组件定义专门的样式编辑器
    const propertyEditors = {
        '布局': {
            properties: [
                {
                    name: 'padding', label: '内边距', type: 'select', options: [
                        {value: '10px', label: '小'},
                        {value: '20px', label: '中'},
                        {value: '30px', label: '大'}
                    ]
                },
                {name: 'background-color', label: '背景色', type: 'color'},
                {
                    name: 'border-style', label: '边框样式', type: 'select', options: [
                        {value: 'none', label: '无'},
                        {value: 'solid', label: '实线'},
                        {value: 'dashed', label: '虚线'}
                    ]
                }
            ]
        },
        '文字': {
            properties: [
                {
                    name: 'text-align', label: '对齐方式', type: 'select', options: [
                        {value: 'left', label: '左对齐'},
                        {value: 'center', label: '居中'},
                        {value: 'right', label: '右对齐'}
                    ]
                },
                {
                    name: 'font-size', label: '字号', type: 'select', options: [
                        {value: '12px', label: '小'},
                        {value: '16px', label: '正常'},
                        {value: '20px', label: '大'},
                        {value: '24px', label: '特大'}
                    ]
                },
                {name: 'color', label: '颜色', type: 'color'}
            ]
        },
        '分割线': {
            properties: [
                {
                    name: 'border-style', label: '样式', type: 'select', options: [
                        {value: 'solid', label: '实线'},
                        {value: 'dashed', label: '虚线'},
                        {value: 'dotted', label: '点线'}
                    ]
                },
                {name: 'border-color', label: '颜色', type: 'color'},
                {
                    name: 'margin', label: '间距', type: 'select', options: [
                        {value: '10px 0', label: '小'},
                        {value: '20px 0', label: '中'},
                        {value: '30px 0', label: '大'}
                    ]
                }
            ]
        },
        '图片': {
            properties: [
                {
                    name: 'text-align', label: '对齐方式', type: 'select', options: [
                        {value: 'left', label: '左对齐'},
                        {value: 'center', label: '居中'},
                        {value: 'right', label: '右对齐'}
                    ]
                },
                {
                    name: 'height', label: '高度', type: 'select', options: [
                        {value: 'auto', label: '自适应'},
                        {value: '200px', label: '200px'},
                        {value: '300px', label: '300px'},
                        {value: '400px', label: '400px'},
                        {value: '500px', label: '500px'}
                    ]
                },
                {
                    name: 'object-fit', label: '填充方式', type: 'select', options: [
                        {value: 'contain', label: '完整显示'},
                        {value: 'cover', label: '裁剪填充'},
                        {value: 'fill', label: '拉伸填充'}
                    ]
                },
                {
                    name: 'border-radius',
                    label: '圆角',
                    type: 'select',
                    target: 'img',
                    options: [
                        {value: '0', label: '无圆角'},
                        {value: '4px', label: '小圆角'},
                        {value: '8px', label: '中圆角'},
                        {value: '16px', label: '大圆角'},
                        {value: '50%', label: '圆形'}
                    ]
                },
            ]
        },
        '按钮': {
            properties: [
                {
                    name: 'text-align', label: '对齐方式', type: 'select', target: '.element-content', options: [
                        {value: 'left', label: '左对齐'},
                        {value: 'center', label: '居中'},
                        {value: 'right', label: '右对齐'}
                    ]
                },
                {
                    name: 'background-color', label: '背景色', type: 'select', options: [
                        {value: '#1890ff', label: '蓝色'},
                        {value: '#52c41a', label: '绿色'},
                        {value: '#f5222d', label: '红色'},
                        {value: '#faad14', label: '黄色'}
                    ]
                },
                {
                    name: 'border-radius', label: '圆角', type: 'select', options: [
                        {value: '2px', label: '小圆角'},
                        {value: '4px', label: '中圆角'},
                        {value: '20px', label: '胶囊形'}
                    ]
                },
                {
                    name: 'padding', label: '大小', type: 'select', options: [
                        {value: '4px 8px', label: '小按钮'},
                        {value: '8px 16px', label: '中按钮'},
                        {value: '12px 24px', label: '大按钮'}
                    ]
                }
            ]
        },
        '卡片': {
            properties: [
                {
                    name: 'text-align', label: '文字对齐', type: 'select', options: [
                        {value: 'left', label: '左对齐'},
                        {value: 'center', label: '居中'},
                        {value: 'right', label: '右对齐'}
                    ]
                },
                {name: 'background-color', label: '背景色', type: 'color'},
                {
                    name: 'border-radius', label: '圆角', type: 'select', options: [
                        {value: '0', label: '无圆角'},
                        {value: '4px', label: '小圆角'},
                        {value: '8px', label: '中圆角'},
                        {value: '16px', label: '大圆角'}
                    ]
                },
                {
                    name: 'box-shadow', label: '阴影', type: 'select', options: [
                        {value: 'none', label: '无阴影'},
                        {value: '0 2px 8px rgba(0,0,0,0.1)', label: '浅阴影'},
                        {value: '0 4px 16px rgba(0,0,0,0.1)', label: '中等阴影'},
                        {value: '0 8px 24px rgba(0,0,0,0.1)', label: '深阴影'}
                    ]
                },
                {
                    name: 'border', label: '边框', type: 'select', options: [
                        {value: 'none', label: '无边框'},
                        {value: '1px solid #eee', label: '细边框'},
                        {value: '2px solid #eee', label: '粗边框'}
                    ]
                }
            ]
        },
        '视频': {
            properties: [
                {
                    name: 'width', label: '宽度', type: 'select', options: [
                        {value: '100%', label: '充满'},
                        {value: '400px', label: '小'},
                        {value: '600px', label: '中'},
                        {value: '800px', label: '大'}
                    ]
                },
                {name: 'src', label: '视频链接', type: 'text'},
                {
                    name: 'border-radius', label: '圆角', type: 'select', options: [
                        {value: '0', label: '无圆角'},
                        {value: '4px', label: '小圆角'},
                        {value: '8px', label: '中圆角'}
                    ]
                }
            ]
        },
        '链接': {
            properties: [
                {
                    name: 'text-align', label: '对齐方式', type: 'select', options: [
                        {value: 'left', label: '左对齐'},
                        {value: 'center', label: '居中'},
                        {value: 'right', label: '右对齐'}
                    ]
                },
                {name: 'href', label: '链接地址', type: 'text'},
                {
                    name: 'color', label: '颜色', type: 'select', options: [
                        {value: '#1890ff', label: '蓝色'},
                        {value: '#52c41a', label: '绿色'},
                        {value: '#f5222d', label: '红色'},
                        {value: '#666666', label: '灰色'}
                    ]
                },
                {
                    name: 'text-decoration', label: '下划线', type: 'select', options: [
                        {value: 'none', label: '无'},
                        {value: 'underline', label: '有'}
                    ]
                },
                {
                    name: 'font-size', label: '字号', type: 'select', options: [
                        {value: '12px', label: '小'},
                        {value: '14px', label: '正常'},
                        {value: '16px', label: '大'}
                    ]
                }
            ]
        }
    };

    // 初始化拖拽事件
    componentItems.forEach(item => {
        item.addEventListener('dragstart', (e) => {
            const type = e.target.closest('.component-item').dataset.type;
            e.dataTransfer.setData('component-type', type);
            e.dataTransfer.effectAllowed = 'move';
        });
    });

    // 画布事件
    canvas.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.stopPropagation();
    });

    canvas.addEventListener('drop', (e) => {
        e.preventDefault();
        e.stopPropagation();

        const type = e.dataTransfer.getData('component-type');
        if (type && componentTemplates[type]) {
            const element = createComponent(type);
            if (element) {
                const editableArea = document.querySelector('.editable-area');
                if (editableArea) {
                    editableArea.appendChild(element);
                }
            }
        }
    });

    // 处理拖拽结束
    function handleDragEnd(e) {
        e.target.classList.remove('dragging');
    }

    // 修改创建组件函数
    function createComponent(type) {
        if (!componentTemplates[type]) return null;

        const wrapper = document.createElement('div');
        wrapper.className = 'editable-component';
        wrapper.dataset.type = type; // 添加类型标记

        // 添加控件
        const controls = document.createElement('div');
        controls.className = 'component-controls';
        controls.innerHTML = `
            <button class="control-btn edit" title="编辑样式">✎</button>
            <button class="control-btn duplicate" title="复制">⎘</button>
            <button class="control-btn delete" title="删除">×</button>
        `;

        // 添加内容
        const content = document.createElement('div');
        content.innerHTML = componentTemplates[type].html;


        wrapper.appendChild(controls);
        wrapper.appendChild(content.firstElementChild);

        // 初始化编辑功能
        initializeEditableComponent(wrapper);

        // 如果是图片组件，初始化上传功能
        if (type === 'image') {
            initializeImageUpload(wrapper);
        }

        return wrapper;
    }

    // 初始化组件
    function initializeElement(element) {
        // 添加删除按钮事件
        const deleteBtn = element.querySelector('.control-btn.delete');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', () => element.remove());
        }

        // 添加选中事件
        element.addEventListener('click', (e) => {
            e.stopPropagation();
            selectElement(element);
        });

        // 如果是文本元素，添加编辑功能
        if (element.dataset.type === 'text') {
            const content = element.querySelector('.element-content');
            if (content) {
                content.addEventListener('dblclick', (e) => {
                    e.stopPropagation();
                    content.focus();
                });
            }
        }
    }

    // 导入功能优化
    if (importBtn) {
        importBtn.addEventListener('click', function () {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.html';
            input.onchange = function (e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        try {
                            const html = e.target.result;
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(html, 'text/html');

                            // 提取并应用样式
                            const styles = doc.getElementsByTagName('style');
                            const links = doc.getElementsByTagName('link');

                            // 处理内联样式
                            Array.from(styles).forEach(style => {
                                const newStyle = document.createElement('style');
                                newStyle.textContent = style.textContent;
                                document.head.appendChild(newStyle);
                            });

                            // 处理外部样式表
                            Array.from(links).forEach(link => {
                                if (link.rel === 'stylesheet') {
                                    const newLink = document.createElement('link');
                                    newLink.rel = 'stylesheet';
                                    newLink.href = link.href;
                                    document.head.appendChild(newLink);
                                }
                            });

                            // 清空当前画布
                            const editableArea = document.querySelector('.editable-area');
                            editableArea.innerHTML = '';

                            // 添加编辑提示
                            const hints = document.createElement('div');
                            hints.className = 'editing-hints';
                            hints.innerHTML = `
                                <div class="hint">
                                    <span>✨ 点击组件进行编辑</span>
                                    <span>🖱️ 拖拽组件调整位置</span>
                                    <span>➕ 从左侧添加新组件</span>
                                </div>
                            `;
                            editableArea.appendChild(hints);

                            // 处理 body 内容
                            const bodyContent = doc.body;
                            processImportedContent(bodyContent, editableArea);

                            // 初始化拖放功能
                            initializeDropZones();

                        } catch (error) {
                            console.error('Import error:', error);
                            alert('导入HTML时发生错误：' + error.message);
                        }
                    };
                    reader.readAsText(file);
                }
            };
            input.click();
        });
    }

    // 修改处理导入的内容函数
    function processImportedContent(sourceNode, targetContainer) {
        Array.from(sourceNode.childNodes).forEach(node => {
            if (node.nodeType === 3) { // 文本节点
                if (node.textContent.trim()) {
                    const wrapper = document.createElement('div');
                    wrapper.className = 'editable-component';
                    const content = document.createElement('div');
                    content.className = 'element-content';
                    content.contentEditable = 'true';
                    content.textContent = node.textContent;
                    addEditControls(wrapper);
                    wrapper.appendChild(content);
                    targetContainer.appendChild(wrapper);
                }
            } else if (node.nodeType === 1) { // 元素节点
                if (['script', 'style', 'link'].includes(node.tagName.toLowerCase())) {
                    return;
                }

                const wrapper = document.createElement('div');
                wrapper.className = 'editable-component';

                const content = document.createElement('div');
                content.className = 'element-content';

                // 复制原始元素的内容和属性
                const element = node.cloneNode(false); // 浅克隆，不包含子节点

                // 复制原始元素的属性
                Array.from(node.attributes).forEach(attr => {
                    element.setAttribute(attr.name, attr.value);
                });

                content.appendChild(element);

                // 递归处理子节点
                if (node.childNodes.length > 0) {
                    processImportedContent(node, element);
                }

                addEditControls(wrapper);
                wrapper.appendChild(content);
                targetContainer.appendChild(wrapper);
            }
        });
    }

    // 修改添加编辑控件函数
    function addEditControls(wrapper) {
        const controls = document.createElement('div');
        controls.className = 'component-controls';
        controls.innerHTML = `
            <button class="control-btn edit" title="编辑样式">✎</button>
            <button class="control-btn duplicate" title="复制">⎘</button>
            <button class="control-btn delete" title="删除">×</button>
        `;
        wrapper.appendChild(controls);

        // 初始化编辑功能
        initializeEditableComponent(wrapper);
    }

    // 修改初始化可编辑组件函数
    function initializeEditableComponent(component) {
        const editBtn = component.querySelector('.control-btn.edit');
        const deleteBtn = component.querySelector('.control-btn.delete');
        const duplicateBtn = component.querySelector('.control-btn.duplicate');

        if (editBtn) {
            editBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                showStyleEditor(component);
            });
        }

        if (deleteBtn) {
            deleteBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                component.remove();
            });
        }

        if (duplicateBtn) {
            duplicateBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                const clone = component.cloneNode(true);
                component.parentNode.insertBefore(clone, component.nextSibling);
                initializeEditableComponent(clone);
            });
        }

        // 添加双击编辑功能
        const content = component.querySelector('.element-content');
        if (content) {
            content.addEventListener('dblclick', (e) => {
                e.stopPropagation();
                const editableElement = content.firstElementChild || content;
                editableElement.contentEditable = 'true';
                editableElement.focus();
            });

            content.addEventListener('blur', (e) => {
                const editableElement = content.firstElementChild || content;
                editableElement.contentEditable = 'false';
            }, true);
        }

        // 添加拖拽功能
        component.draggable = true;
        component.addEventListener('dragstart', (e) => {
            e.stopPropagation();
            e.dataTransfer.setData('text/plain', 'move');
            component.classList.add('dragging');
        });

        component.addEventListener('dragend', () => {
            component.classList.remove('dragging');
        });

        // 添加拖放区域
        component.addEventListener('dragover', (e) => {
            e.preventDefault();
            const rect = component.getBoundingClientRect();
            const mouseY = e.clientY - rect.top;

            if (mouseY < rect.height / 2) {
                component.classList.add('drop-before');
                component.classList.remove('drop-after');
            } else {
                component.classList.add('drop-after');
                component.classList.remove('drop-before');
            }
        });

        component.addEventListener('dragleave', () => {
            component.classList.remove('drop-before', 'drop-after');
        });

        component.addEventListener('drop', (e) => {
            e.preventDefault();
            e.stopPropagation();

            const draggingElement = document.querySelector('.dragging');
            if (draggingElement) {
                if (component.classList.contains('drop-before')) {
                    component.parentNode.insertBefore(draggingElement, component);
                } else {
                    component.parentNode.insertBefore(draggingElement, component.nextSibling);
                }
            }

            component.classList.remove('drop-before', 'drop-after');
        });
    }

    // 修改样式编辑器显示函数
    function showStyleEditor(component) {
        const type = component.dataset.type;
        if (!type || !componentTemplates[type]) return;

        const propertyType = componentTemplates[type].properties[0];
        const editor = propertyEditors[propertyType];
        if (!editor) return;

        const styleEditor = document.createElement('div');
        styleEditor.className = 'style-editor';

        let html = `
            <div class="style-editor-header">
                <h3>${propertyType}样式</h3>
                <button class="close-btn">×</button>
            </div>
            <div class="style-editor-content">
        `;

        editor.properties.forEach(prop => {
            const content = component.querySelector('.element-content');
            const element = content.firstElementChild;
            const currentValue = window.getComputedStyle(element)[prop.name];


            html += `<div class="style-item">
                <label>${prop.label}</label>`;

            if (prop.type === 'select') {
                html += `<select data-style="${prop.name}">
                    ${prop.options.map(option =>
                    `<option value="${option.value}" ${currentValue === option.value ? 'selected' : ''}>
                            ${option.label}
                        </option>`
                ).join('')}
                </select>`;
            } else if (prop.type === 'color') {
                html += `<input type="${prop.type}" data-style="${prop.name}" value="${currentValue}">`;
            } else if (prop.type === 'text') {
                const value = element.tagName === 'A' ? element.href :
                    element.tagName === 'IFRAME' ? element.src : '';
                html += `<input type="text" data-style="${prop.name}" value="${value}" placeholder="请输入${prop.label}">`;
            }

            html += `</div>`;
        });

        html += '</div>';
        styleEditor.innerHTML = html;

        // 添加事件处理
        styleEditor.querySelector('.close-btn').addEventListener('click', () => {
            styleEditor.remove();
        });

        const inputs = styleEditor.querySelectorAll('input, select');

        inputs.forEach(input => {
            input.addEventListener('change', () => {
                const content = component.querySelector('.element-content');
                const element = content.firstElementChild;
                const styleName = input.dataset.style;
                const value = input.value;
                // 关键修改开始 ------------------------------
                if (component.dataset.type === 'image' && styleName === 'border-radius') {
                    // 针对图片圆角的特殊处理
                    const img = component.querySelector('img');
                    const wrapper = component.querySelector('.image-wrapper');
                    if (img && wrapper) {
                        img.style[styleName] = value;  // 将圆角应用到img元素
                        wrapper.style.overflow = 'hidden';  // 确保裁剪生效
                    }
                } else {
                    // 原有逻辑保持不变
                    const parentDiv = component.querySelector('.element-content');
                    if (parentDiv) {
                        parentDiv.style[styleName] = value;
                    }
                }

                // 关键：获取外层 div.element-content
                const parentDiv = component.querySelector('.element-content');
                if (parentDiv) {
                    parentDiv.style[styleName] = value;
                }


                if (styleName === 'href' && element.tagName === 'A') {
                    element.href = value;
                } else if (styleName === 'src' && type === 'video') {
                    const iframe = document.createElement('iframe');
                    iframe.style.width = '100%';
                    iframe.style.height = '100%';
                    iframe.style.border = 'none';
                    iframe.src = value;
                    const placeholder = content.querySelector('.video-placeholder');
                    placeholder.innerHTML = '';
                    placeholder.appendChild(iframe);
                } else {
                    element.style[styleName] = value;
                }
            });
        });

        document.body.appendChild(styleEditor);
    }

    // 选中元素
    function selectElement(element) {
        if (selectedElement) {
            selectedElement.classList.remove('selected');
        }
        selectedElement = element;
        element.classList.add('selected');
        showProperties(element);
    }

    // 显示属性面板
    function showProperties(element) {
        const type = element.dataset.type;
        if (!type || !componentTemplates[type]) return;

        const properties = componentTemplates[type].properties;
        const propertiesPanel = document.querySelector('.properties-content');

        let html = `<div class="property-group">`;
        properties.forEach(prop => {
            const value = element.style[prop] || '';
            html += `
                <div class="property-item">
                    <label>${prop}</label>
                    <input type="text" data-property="${prop}" value="${value}">
                </div>
            `;
        });
        html += '</div>';
        propertiesPanel.innerHTML = html;

        // 添加属性更新事件
        const inputs = propertiesPanel.querySelectorAll('input');
        inputs.forEach(input => {
            input.addEventListener('change', function () {
                if (selectedElement) {
                    selectedElement.style[this.dataset.property] = this.value;
                }
            });
        });
    }

    // 添加图片上传处理
    // 修改 initializeImageUpload 函数中的元素选择方式
    function initializeImageUpload(element) {
        // 使用更精确的选择器定位图片和输入框
        const imgElement = element.querySelector('.image-wrapper img');
        const inputElement = element.querySelector('.image-wrapper input[type="file"]');
        const uploadText = element.querySelector('.upload-text');

        if (imgElement && inputElement) {
            imgElement.addEventListener('click', () => {
                inputElement.click();
            });

            inputElement.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function (e) {
                        imgElement.src = e.target.result;
                        if (uploadText) {
                            uploadText.style.display = 'none';
                        }
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
    }

    // 添加初始化拖放区域的函数
    function initializeDropZones() {
        const editableComponents = document.querySelectorAll('.editable-component');
        editableComponents.forEach(component => {
            component.addEventListener('dragover', handleDragOver);
            component.addEventListener('drop', handleDrop);
            component.addEventListener('dragleave', handleDragLeave);
        });
    }

    // 处理拖拽悬停
    function handleDragOver(e) {
        e.preventDefault();
        e.stopPropagation();

        const rect = this.getBoundingClientRect();
        const mouseY = e.clientY - rect.top;

        this.classList.remove('drop-before', 'drop-after');
        if (mouseY < rect.height / 2) {
            this.classList.add('drop-before');
        } else {
            this.classList.add('drop-after');
        }
    }

    // 处理拖拽离开
    function handleDragLeave(e) {
        this.classList.remove('drop-before', 'drop-after');
    }

    // 处理拖放
    function handleDrop(e) {
        e.preventDefault();
        e.stopPropagation();

        const type = e.dataTransfer.getData('component-type');
        if (type && componentTemplates[type]) {
            const newElement = createComponent(type);
            if (newElement) {
                if (this.classList.contains('drop-before')) {
                    this.parentNode.insertBefore(newElement, this);
                } else {
                    this.parentNode.insertBefore(newElement, this.nextSibling);
                }
                initializeEditableComponent(newElement);
            }
        }

        this.classList.remove('drop-before', 'drop-after');
    }

    // 修改导出功能
    if (exportBtn) {
        exportBtn.addEventListener('click', async function () {
            try {
                // 检查导出权限
                const permissionResponse = await fetch('/api/v1/userTemplates/check-export-permission', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                const permissionData = await permissionResponse.json();

                if (!permissionData.data.isExport) {
                    alert('您没有导出权限，请联系管理员开通权限。');
                    return;
                }

                // 有权限，继续执行导出逻辑
                const editableArea = document.querySelector('.editable-area');
                const clonedContent = editableArea.cloneNode(true);

// 清理虚线/点线边框
                clonedContent.querySelectorAll('[style*="dashed"], [style*="dotted"]').forEach(el => {
                    el.style.border = 'none';
                });

// 1. 移除所有可编辑属性
                clonedContent.querySelectorAll('[contenteditable]').forEach(el => {
                    el.removeAttribute('contenteditable');
                });

// 2. 移除所有事件监听器
                const cleanEl = el => {
                    const newEl = el.cloneNode(true);
                    el.parentNode.replaceChild(newEl, el);
                    return newEl;
                };
                clonedContent.querySelectorAll('*').forEach(cleanEl);

// 3. 修正超链接
                clonedContent.querySelectorAll('a').forEach(link => {
                    let href = link.getAttribute('href');
                    if (href && !/^https?:\/\//.test(href)) {
                        if (href.startsWith('www.')) {
                            href = `http://${href}`;
                        }
                        link.setAttribute('href', href);
                    }
                    link.ondblclick = null;
                });

// ============= 新增按钮居中修复逻辑开始 =============
// 3.1 修复段落中的块级元素嵌套
                clonedContent.querySelectorAll('p').forEach(p => {
                    // 移除直接子元素中的.editable-component包裹
                    const badDivs = p.querySelectorAll(':scope > div.editable-component');
                    badDivs.forEach(div => {
                        // 使用文档片段保留原有子元素
                        const fragment = document.createDocumentFragment();
                        while (div.firstChild) {
                            const child = div.firstChild;
                            // 保留文本节点和元素节点
                            if (child.nodeType === Node.TEXT_NODE || child.nodeType === Node.ELEMENT_NODE) {
                                fragment.appendChild(child);
                            }
                        }
                        // 插入原始内容并移除多余div
                        p.insertBefore(fragment, div);
                        div.remove();
                    });

                    // 保留段落基础样式
                    p.style.cssText += '; margin: 10px 0;';
                });

// 3.2 按钮容器处理
                clonedContent.querySelectorAll('a.button').forEach(button => {
                    // 检查是否需要创建容器
                    const parent = button.parentElement;
                    const isAlreadyWrapped =
                        parent.style.textAlign === 'center' ||
                        parent.classList.contains('button-container');

                    if (!isAlreadyWrapped) {
                        // 创建居中容器
                        const wrapper = document.createElement('div');
                        wrapper.style.cssText = `
            text-align: center;
            margin: 20px 0;
            width: 100%;
        `;
                        // 插入新容器并移动按钮
                        parent.insertBefore(wrapper, button);
                        wrapper.appendChild(button);
                    }
                });
// ============= 新增按钮居中修复逻辑结束 =============

// 4. 保留关键样式
                clonedContent.querySelectorAll('.element-content').forEach(el => {
                    const keepStyles = ['text-align', 'display', 'flex-direction', 'justify-content'];
                    Array.from(el.style).forEach(styleName => {
                        if (!keepStyles.includes(styleName)) {
                            el.style.removeProperty(styleName);
                        }
                    });
                    el.classList.remove('element-content');
                });

// 5. 清理图片上传残留
                clonedContent.querySelectorAll('.image-wrapper').forEach(wrapper => {
                    wrapper.querySelector('input[type="file"]')?.remove();
                    wrapper.querySelector('.upload-text')?.remove();
                    wrapper.style.cursor = 'default';
                });

// 收集所有样式
                let allStyles = '';

// 1. 收集页面样式表
                Array.from(document.styleSheets).forEach(sheet => {
                    try {
                        const rules = sheet.cssRules || sheet.rules;
                        Array.from(rules).forEach(rule => {
                            allStyles += rule.cssText + '\n';
                        });
                    } catch (e) {
                        console.warn('Cannot read stylesheet:', e);
                    }
                });

// 2. 收集组件样式
                let componentStyles = '';
                const components = clonedContent.querySelectorAll('.editable-component');
                components.forEach(component => {
                    const content = component.querySelector('.element-content');
                    if (content) {
                        const actualContent = content.firstElementChild;
                        if (actualContent) {
                            const className = `exported-${component.dataset.type}-${Date.now()}`;
                            actualContent.classList.add(className);

                            // 处理内联样式
                            const styles = actualContent.getAttribute('style');
                            if (styles) {
                                componentStyles += `.${className} { ${styles} }\n`;
                            }

                            // 处理容器样式
                            const containerStyles = content.getAttribute('style');
                            if (containerStyles) {
                                componentStyles += `.${className}-container { ${containerStyles} }\n`;
                                const containerDiv = document.createElement('div');
                                containerDiv.className = `${className}-container`;
                                component.parentNode.replaceChild(containerDiv, component);
                                containerDiv.appendChild(actualContent);
                            } else {
                                component.parentNode.replaceChild(actualContent, component);
                            }
                        }
                    }
                });

// ============= 新增按钮保护样式 =============
                const buttonProtectCSS = `
/* 按钮保护样式 */
a.button {
    display: inline-block !important;
    margin: 20px auto !important;
    text-align: center !important;
    position: relative;
    z-index: 1;
}

@media (max-width: 768px) {
    a.button {
        width: 90% !important;
        padding: 12px !important;
    }
}`;

// 移除编辑相关元素
                clonedContent.querySelector('.editing-hints')?.remove();
                clonedContent.querySelectorAll('.component-controls').forEach(control => control.remove());

// 生成最终HTML
                const htmlContent = `
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>导出的页面</title>
    <style>
        /* 按钮保护样式 */
        ${buttonProtectCSS}

        /* 原始样式 */
        ${allStyles}

        /* 组件样式 */
        ${componentStyles}

        /* 基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.5;
            color: #333;
        }
        img {
            max-width: 100%;
            height: auto;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* 响应式样式 */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            img {
                max-width: 100% !important;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        ${clonedContent.innerHTML}
    </div>
</body>
</html>`;

// 此处应继续执行导出操作（如下载文件等）

                // 创建下载链接
                const blob = new Blob([htmlContent], {type: 'text/html'});
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'exported-page.html';
                document.body.appendChild(a);
                a.click();

                // 清理
                setTimeout(() => {
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }, 0);
            } catch (error) {
                console.error('检查导出权限失败:', error);
                alert('检查导出权限失败，请稍后重试。');
            }
        });
    }

    // 添加组件的事件处理
    function initializeComponent(component) {
        const type = component.dataset.type;

        // 图片上传处理
        if (type === 'image') {
            const input = component.querySelector('input[type="file"]');
            const img = component.querySelector('img');
            const uploadText = component.querySelector('.upload-text');

            img.addEventListener('click', () => input.click());

            input.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        img.src = e.target.result;
                        uploadText.style.display = 'none';
                    };
                    reader.readAsDataURL(file);
                }
            });
        }

        // 视频链接处理
        if (type === 'video') {
            const input = component.querySelector('input[type="text"]');
            const placeholder = component.querySelector('.video-placeholder');

            input.addEventListener('change', () => {
                const url = input.value.trim();
                if (url) {
                    const iframe = document.createElement('iframe');
                    iframe.style.width = '100%';
                    iframe.style.height = '100%';
                    iframe.style.border = 'none';
                    iframe.src = url;
                    placeholder.innerHTML = '';
                    placeholder.appendChild(iframe);
                }
            });
        }

        // 图标选择处理
        if (type === 'icon') {
            const select = component.querySelector('select');
            const display = component.querySelector('.icon-display');
            const icons = {
                star: '★',
                heart: '♥',
                arrow: '→'
            };

            select.addEventListener('change', () => {
                display.textContent = icons[select.value];
            });
        }

        // 链接处理
        if (type === 'link') {
            const input = component.querySelector('input');
            const link = component.querySelector('a');

            input.addEventListener('change', () => {
                const url = input.value.trim();
                if (url) {
                    link.href = url;
                }
            });
        }
    }

    // ================== 表单提交处理 ==================
    document.getElementById('send-form').addEventListener('submit', async function (e) {
        e.preventDefault();

        // 表单数据校验
        const fromEmail = document.getElementById('send-from').value.trim();
        const password = document.getElementById('send-password').value.trim();
        const toEmail = document.getElementById('send-to').value.trim();
        const subject = document.getElementById('send-subject').value.trim();
        const files = fileInput.files;

        if (!fromEmail || !password || !toEmail || !subject) {
            return showToast('❌ 请填写所有必填项');
        }

        try {
            // 有权限，继续执行导出逻辑
            const editableArea = document.querySelector('.editable-area');
            // 替换原来的克隆逻辑
            const clonedContent = editableArea.cloneNode(true);
            // 在克隆后添加：
            clonedContent.querySelectorAll('[style*="dashed"], [style*="dotted"]').forEach(el => {
                el.style.border = 'none';
            });

// 新增以下处理步骤：
// 1. 移除所有可编辑属性
            clonedContent.querySelectorAll('[contenteditable]').forEach(el => {
                el.removeAttribute('contenteditable');
            });

// 2. 移除所有事件监听器（需要记录原有事件）
            const cleanEl = el => {
                const newEl = el.cloneNode(true);
                el.parentNode.replaceChild(newEl, el);
                return newEl;
            };
            clonedContent.querySelectorAll('*').forEach(cleanEl);

// 3. 修正超链接（在生成htmlContent之前添加）
            clonedContent.querySelectorAll('a').forEach(link => {
                let href = link.getAttribute('href');

                // 修复相对路径问题
                if (href && !/^https?:\/\//.test(href)) {
                    if (href.startsWith('www.')) {
                        href = `http://${href}`;
                    }
                    link.setAttribute('href', href);
                }

                // 移除双击编辑事件残留
                link.ondblclick = null;
            });

            // 4. 保留关键样式
            clonedContent.querySelectorAll('.element-content').forEach(el => {
                // 保留 text-align 和布局相关样式
                const keepStyles = ['text-align', 'display', 'flex-direction', 'justify-content'];
                const currentStyles = el.style;

                // 移除非关键样式
                Array.from(currentStyles).forEach(styleName => {
                    if (!keepStyles.includes(styleName)) {
                        el.style.removeProperty(styleName);
                    }
                });

                el.classList.remove('element-content');
            });

// 5. 清理图片上传残留
            clonedContent.querySelectorAll('.image-wrapper').forEach(wrapper => {
                wrapper.querySelector('input[type="file"]')?.remove();
                wrapper.querySelector('.upload-text')?.remove();
                wrapper.style.cursor = 'default';
            });

            // 收集所有样式
            let allStyles = '';

            // 1. 收集页面中所有的样式表
            const styleSheets = document.styleSheets;
            Array.from(styleSheets).forEach(sheet => {
                try {
                    const rules = sheet.cssRules || sheet.rules;
                    Array.from(rules).forEach(rule => {
                        allStyles += rule.cssText + '\n';
                    });
                } catch (e) {
                    console.warn('Cannot read stylesheet:', e);
                }
            });

            // 2. 收集组件样式
            let componentStyles = '';
            const components = clonedContent.querySelectorAll('.editable-component');
            components.forEach(component => {
                const content = component.querySelector('.element-content');
                if (content) {
                    const actualContent = content.firstElementChild;
                    if (actualContent) {
                        const styles = actualContent.getAttribute('style');
                        const className = `exported-${component.dataset.type}-${Date.now()}`;
                        actualContent.classList.add(className);
                        if (styles) {
                            componentStyles += `.${className} { ${styles} }\n`;
                        }

                        const containerStyles = content.getAttribute('style');
                        if (containerStyles) {
                            componentStyles += `.${className}-container { ${containerStyles} }\n`;
                            const containerDiv = document.createElement('div');
                            containerDiv.className = `${className}-container`;
                            component.parentNode.replaceChild(containerDiv, component);
                            containerDiv.appendChild(actualContent);
                        } else {
                            component.parentNode.replaceChild(actualContent, component);
                        }
                    }
                }
            });

            // 移除编辑相关的元素
            const hints = clonedContent.querySelector('.editing-hints');
            if (hints) hints.remove();

            const controls = clonedContent.querySelectorAll('.component-controls');
            controls.forEach(control => control.remove());

            // 生成HTML文档
            const htmlContent = `
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>导出的页面</title>
    <style>
        /* 导入的原始样式 */
        ${allStyles}
        
        /* 组件样式 */
        ${componentStyles}
        
        /* 基础样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.5;
            color: #333;
        }
        img {
            max-width: 100%;
            height: auto;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* 响应式样式 */
        @media (max-width: 768px) {
            .container {
                padding: 15px;
            }
            img {
                max-width: 100% !important;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        ${clonedContent.innerHTML}
    </div>
</body>
</html>`;
            if (!htmlContent) return showToast('❌ 邮件内容不能为空');

            // 构建FormData
            const formData = new FormData();
            formData.append('fromEmail', fromEmail);
            formData.append('smtpPassword', password);
            formData.append('toEmail', toEmail);
            formData.append('subject', subject);
            formData.append('htmlContent', htmlContent);

            // 添加附件
            Array.from(files).forEach(file => {
                formData.append('attachments', file);
            });

            // 更新按钮状态
            const sendBtn = this.querySelector('[type="submit"]');
            sendBtn.disabled = true;
            sendBtn.innerHTML = '<div class="spinner"></div> 发送中...';

            // 发送请求
            const response = await fetch('/api/v1/emails/send', {
                method: 'POST',
                body: formData
            });

            // 处理响应
            const result = await response.json();
            if (response.ok) {
                showToast('✅ 邮件发送成功');
                sendModal.style.display = 'none';
            } else {
                throw new Error(result.message || '发送失败');
            }
        } catch (error) {
            showToast(`❌ ${error.message}`);
        } finally {
            const sendBtn = document.querySelector('#send-form [type="submit"]');
            sendBtn.disabled = false;
            sendBtn.textContent = '立即发送';
        }
    });

// 关闭模态框
    sendModal.querySelectorAll('.close, #cancel-send').forEach(btn => {
        btn.addEventListener('click', () => {
            sendModal.style.display = 'none';
        });
    });

    // 添加错误处理的工具函数
    async function checkApiResponse(response) {
        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status}`);
        }
        const data = await response.json();
        if (data.code !== 200) {
            throw new Error(data.message || '请求失败');
        }
        return data;
    }
});